package com.service;

import javax.servlet.http.HttpSession;

import com.config.WebConfig;
import com.hdb.DB;
import com.hdb.TAdmin;
import com.hdb.TUser;
import com.hdb.dao.Hib;
import com.util.Check;
import org.apache.struts2.ServletActionContext;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

public class LoginService extends BasicService {

    public String adminLogin(String adminName, String adminPw) {
        TAdmin admin = db.findAdmin(adminName, adminPw);//获得admin
        if (admin == null) {
            return sendJSON(new E("用户名或密码错误"));
        }
        HttpSession session = getSession();
        session.setMaxInactiveInterval(10000000);
        session.setAttribute("admin", admin);
        session.setAttribute("admin.permission", Check.getPermissionArray(admin.getAdminLevel()));
        return sendJSON(new E(null, WebConfig.RootPath + "/admin/index.jsp"));
    }

    public String login(String userName, String userPw) {
        TUser user = db.findUser(userName, userPw);
        if (user == null) {
            return sendJSON(new E("用户名或密码错误"));
        }
        HttpSession session = getSession();
        session.setAttribute("user", user);
        return sendJSON(new E(null, WebConfig.RootPath + "/"));
    }

    public String adminLogout() {
        WebContext ctx = WebContextFactory.get();
        HttpSession session = ctx.getSession();
        TAdmin admin = (TAdmin) session.getAttribute("admin");
        if (admin == null) return sendJSON(new E("非管理员账户,无需登出后台"));
        session.removeAttribute("admin");
        session.removeAttribute("admin.permission");
        return sendJSON(new E(null, WebConfig.RootPath + "/login.jsp"));
    }

    public String logout() {
        WebContext ctx = WebContextFactory.get();
        HttpSession session = ctx.getSession();
        TAdmin admin = (TAdmin) session.getAttribute("user");
        if (admin == null) return sendJSON(new E("尚未登录,无需登出"));
        session.removeAttribute("user");
        return sendJSON(new E(null, WebConfig.RootPath + "/login.jsp"));//TODO:设置正确路径
    }

    @Override
    Hib getDAO() {
        return db.adminDAO;
    }
}
